/**
 试题
*/
<template>
    <div>
        <div v-if="indexKey === 1">
            <el-row type="flex" class="row-bg" justify="space-between">
                <div>
                    <span @click="reback" class="p_cals">
                        {{ $t('examinationManagement.questionBankManagement') }}
                    </span>
                    /
                    <span>{{ $t(this.$route.query.id.questionPoolName) }}</span>
                </div>
                <el-button @click="reback">
                    {{ $t('examinationManagement.back') }}
                </el-button>
            </el-row>

            <el-card
                shadow="never"
                v-loading="loading"
                body-style="padding: 24px;"
                class="card-margin"
            >
                <div class="float-left associated-conditional-input">
                    <KeywordInput
                        v-model="queryForm.condition.questionName"
                        :placeholder="$t('examinationManagement.titlequestion')"
                        @enter="onSubmit"
                    />
                </div>
                <div class="edu-opertion-bar sub-title">
                    <div class="float-right" style="display: flex;">
                        <el-button style="margin-left:10px" type="primary" @click="exportFile">
                            {{ $t('examinationManagement.batchExport') }}
                        </el-button>
                        <el-dropdown
                            style="margin-right:10px"
                            placement="bottom-start"
                            trigger="click"
                            @command="leadFile"
                        >
                            <el-button type="primary">
                                {{ $t('examinationManagement.batchImport') }}
                                <i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="导入">
                                    {{ $t('examinationManagement.lead') }}
                                </el-dropdown-item>
                                <el-dropdown-item command="下载">
                                    {{ $t('examinationManagement.download') }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-upload
                            v-model="dialogForm.file"
                            class="upload-demo"
                            :action="action"
                            :data="{ questionPoolId: $route.query.id.questionPoolId }"
                            :auto-upload="true"
                            :before-upload="beforeUpload"
                            :on-success="changeSuccess"
                            :file-list="fileList"
                            style="display: none;"
                        >
                            <span slot="trigger" ref="importBtn">
                                {{ $t('graduate.clickUpload') }}
                            </span>
                        </el-upload>
                        <el-button type="danger" @click="batchDeleteClick">
                            {{ $t('examinationManagement.delete') }}
                        </el-button>
                        <el-button type="primary" @click="exportAdd">
                            {{ $t('examinationManagement.newQuestions') }}
                        </el-button>
                    </div>
                </div>
                <edu-table
                    :pagination="false"
                    :tooltipEffect="tooltipEffect"
                    stripe
                    :data="dataList"
                    size="mini"
                    @selection-change="handleSelectionChange"
                >
                    <edu-table-column
                        :label="$t('examinationManagement.testQuestion')"
                        prop="questionName"
                    ></edu-table-column>
                    <edu-table-column
                        :label="$t('examinationManagement.questionType')"
                        prop="questionType"
                    >
                        <template slot-scope="props">
                            <span v-if="props.row.questionType == 1">
                                {{ $t('examinationManagement.singleQuestions') }}
                            </span>
                        </template>
                    </edu-table-column>
                    <edu-table-column
                        :label="$t('examinationManagement.updateTime')"
                        prop="updateTime"
                    ></edu-table-column>
                    <edu-table-column :label="$t('examinationManagement.operate')" fit>
                        <template slot-scope="props">
                            <el-button type="text" @click="editOutline(props.row)">
                                {{ $t('examinationManagement.edit') }}
                            </el-button>
                            <el-button type="text" @click="deteOutline(props.row)">
                                {{ $t('examinationManagement.delete') }}
                            </el-button>
                            <el-button type="text" @click="detailsOutline(props.row)">
                                {{ $t('examinationManagement.check') }}
                            </el-button>
                        </template>
                    </edu-table-column>
                </edu-table>
                <el-row type="flex" class="row-bg" justify="end">
                    <el-col>
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="queryForm.pageNum_"
                            :page-sizes="[20, 40, 80, 100]"
                            :page-size="queryForm.pageSize_"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="queryForm.total_"
                            style="float:right;margin-top:10px"
                        ></el-pagination>
                    </el-col>
                </el-row>
            </el-card>
            <!-- 新建题库 -->
            <el-dialog
                @close="dataObjit = {}"
                :before-close="beforeClose"
                :title="titleList"
                width="60%"
                :visible.sync="addflag"
                :show-close="beforeClose"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <testQuestionsAdd
                    ref="addform"
                    @cancel-dialog="changeClose"
                    :dataQueryForm="dataQueryForm"
                    :dataQuery="dataQuery"
                    :showFlag="addflag"
                    :dataProp="dataProp"
                    :dataListProp="dataObjit"
                    @close="
                        flag => {
                            addflag = flag
                        }
                    "
                    @affirm-form="addrmForm"
                ></testQuestionsAdd>
            </el-dialog>
            <!-- 编辑题库 -->
            <el-dialog
                @close="dataEdit = {}"
                :before-close="editClose"
                :title="titleList"
                width="60%"
                :visible.sync="editflag"
                :show-close="editClose"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <testQuestionsEdit
                    ref="editform"
                    @cancel-eidt="dialogClose"
                    :dataQuery="dataQuery"
                    :dataList="queryForm"
                    :dataProp="editProp"
                    :showFlag="editflag"
                    :dataListProp="dataEdit"
                    @close="
                        flag => {
                            editflag = false
                        }
                    "
                    @affirm-edit="editrmForm"
                ></testQuestionsEdit>
            </el-dialog>
            <!-- 查看 -->
            <el-dialog
                @close="dataView = {}"
                :before-close="viewClose"
                :title="titleList"
                width="60%"
                :visible.sync="viewFlag"
                :show-close="viewClose"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
            >
                <testQuestionsView
                    ref="viewform"
                    :dataProp="viewProp"
                    @cancel-view="viewsClose"
                    :dataListProp="dataView"
                    :dataQuery="dataQuery"
                    :showFlag="viewFlag"
                    @close="
                        flag => {
                            viewFlag = false
                        }
                    "
                ></testQuestionsView>
            </el-dialog>
            <edu-export-dialog
                :disabled="exportButton"
                :title="$t('message.prompt')"
                ref="downloadRef"
                :data="exportResult"
            ></edu-export-dialog>
        </div>
    </div>
</template>
<script>
import { queryDic } from 'common/src/api/dictionary'
import UTILS from 'common/src/utils/utils'
import testQuestionsAdd from 'common/src/views/academicBehaviorNorms/examination/common/testQuestionsAdd'
import testQuestionsEdit from 'common/src/views/academicBehaviorNorms/examination/common/testQuestionsEdit'
import testQuestionsView from 'common/src/views/academicBehaviorNorms/examination/common/testQuestionsView'
import graduateStudent from 'common/src/api/graduateStudent/graduateStudent'
import { getALLCollege } from 'common/src/api/internationalExchanges/exchangeCollegeManagement'
import forumProject from 'common/src/api/academicForums/forumProject'
import examinationManagement from 'common/src/api/academicBehaviorNorms/examination/examinationManagement'
import baseUrl from 'common/src/api/academicBehaviorNorms/examination/env'

export default {
    components: {
        testQuestionsAdd,
        testQuestionsEdit,
        testQuestionsView
    },
    data() {
        return {
            indexKey: 1, // 面包屑
            importConference: false, // 是否显示导入框
            ifErr: false, // 是否展示错误信息
            uploadConfig: {
                fileList: [],
                data: { versionCode: '' }
            },
            applyForm: {
                attachFile: [],
                attachName: []
            },
            fileList: [],
            fileFlag: true,
            title: '',
            titleList: '',
            dataListObj: {},
            addflag: false,
            editflag: false,
            viewFlag: false,
            exportButton: false,
            exportResult: null,
            dataList: [],
            multipleSelection: [],
            queryForm: {
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    questionPoolId: this.$route.query.id.questionPoolId,
                    questionName: ''
                }
            },
            // 导入
            exportForm: {},
            // 导入失败列表
            errList: [],
            dialogForm: {
                file: ''
            },
            action: '',
            data: {},
            dataProp: '',
            dataListProp: {},
            dataQueryForm: {},
            dataQuery: {},
            dataEdit: [],
            dataView: [],
            options: {
                facultys: [],
                timeList: [],
                title: [],
                sex: [],
                regionList: []
            },
            id: ''
        }
    },
    watch: {},
    created() {
        this.postListQuestion(this.queryForm)
    },
    filters: {},
    mounted() {
        this.getOptions()
        this.action = `${baseUrl}/behavior/behaviorquestion/importQuestion`
    },
    methods: {
        // 查询列表
        postListQuestion(date) {
            examinationManagement.listQuestion(date).then(res => {
                this.queryForm.total_ = res.data.total_
                this.dataList = res.data.list
            })
        },
        // 导入
        leadFile(command) {
            if (command === '导入') {
                this.$refs.importBtn.click()
            } else if (command === '下载') {
                examinationManagement.downloadTemplate().then(res => {
                    this.$message({
                        type: 'success',
                        message: this.$t('internship.successfully')
                    })
                })
            }
        },
        // 新增
        exportAdd() {
            this.dataProp = '新增'
            this.titleList = this.$t('新建')
            this.dataQueryForm = this.queryForm
            this.dataQuery = this.$route.query.id
            this.addflag = true
        },
        // 新增取消
        changeClose(param) {
            this.addflag = param
        },
        // 新增关闭
        beforeClose(param) {
            this.$refs.addform.cancelDialog()
        },
        // 新增保存
        addrmForm(data, dateList) {
            examinationManagement.addQuestion(data).then(res => {
                this.$message.success(this.$t('internship.successfully'))
                this.$refs.addform.confirmInner()
                this.queryForm.pageNum_ = 1
                this.postListQuestion(this.queryForm)
            })
        },
        // 编辑
        editOutline(row) {
            let params = {
                id: row.id
            }
            examinationManagement.getQuestionDetail(params).then(res => {
                this.editProp = '编辑'
                this.titleList = this.$t('编辑')
                this.dataEdit = res.data
                this.dataQuery = this.$route.query.id
                this.editflag = true
            })
        },
        // 编辑取消
        dialogClose() {
            this.editflag = false
        },
        // 编辑关闭
        editClose() {
            this.$refs.editform.cancelDialog()
        },
        // 编辑保存
        editrmForm(data) {
            data['answerList'] = data['answerList'].map(item => {
                item['optionCode'] = item['label']
                item['optionContent'] = item['value']
                return item
            })
            examinationManagement.editQuestion(data).then(res => {
                this.$message.success(this.$t('internship.successfully'))
                this.$refs.editform.confirmInner()
                this.editflag = false
                this.postListQuestion(this.queryForm)
            })
        },
        // 查看详情
        detailsOutline(row) {
            let param = {
                id: row.id
            }
            examinationManagement.getQuestionDetail(param).then(res => {
                this.viewProp = '查看'
                this.titleList = this.$t('查看')
                this.dataView = res.data
                this.viewFlag = true
            })
        },
        // 查看取消
        viewsClose() {
            this.viewFlag = false
        },
        // 查看关闭
        viewClose() {
            this.$refs.viewform.cancelDialog()
        },
        // 批量删除
        batchDeleteClick() {
            if (this.multipleSelection.length > 0) {
                let deleteArray = this.multipleSelection.map(item => {
                    return item.id
                })
                this.$delConfirm(this.$t('message.areYouSureDelete'), this.$t('message.prompt'), {
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: 'warning'
                }).then(() => {
                    examinationManagement
                        .deleteQuestion({
                            questionPoolId: this.$route.query.id.questionPoolId,
                            idList: deleteArray
                        })
                        .then(res => {
                            if (res.code === 200) {
                                this.$message.success(this.$t('删除成功'))
                                this.onSubmit()
                            }
                        })
                })
            } else {
                this.$message.error(this.$t('请勾选数据'))
            }
        },
        // 单个删除
        deteOutline(row) {
            this.$delConfirm(this.$t('您确定要删除吗？')).then(_ => {
                examinationManagement
                    .deleteQuestion({ questionPoolId: row.questionPoolId, idList: [row.id] })
                    .then(res => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('externamExchangeBase.operateSuccessfully')
                            })
                            this.onSubmit()
                        }
                    })
            })
        },
        getOptions() {
            // 筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['profession', 'G_XBIE']
            }
            queryDic(data).then(res => {
                UTILS.fillSelect(
                    {
                        title: 'profession',
                        sex: 'G_XBIE'
                    },
                    res.data,
                    this.options
                )
            })
        },
        // 上传数据
        handlerUploadSuccess(response, file, fileList) {
            this.errList = []
            let responseCode = response.code
            let _this = this
            if (responseCode === 200) {
                // 导入成功
                _this.$message({
                    message: _this.$t('base.importSuccess'),
                    type: 'success'
                })
                // 展示导入错误 的信息
                if (response.data) {
                    _this.ifErr = true
                    response.data.forEach(err => {
                        _this.errList.push(err)
                    })
                }
            } else if (response.msg) {
                _this.$message.error(response.msg)
            }
            this.postListQuestion(this.queryForm)
        },

        handlerBeforeRemove(file, fileList) {
            if (this.fileFlag) {
                return this.$delConfirm().then(_ => {})
            }
        },
        handlerRemove(file, fileList) {
            this.errList = []
            this.ifErr = false
            let index = this.applyForm.attachFile.indexOf(file.url)
            this.applyForm.attachFile.splice(index, 1)
            this.applyForm.attachName.splice(index, 1)
        },
        handlerUploadError(response, file, fileList) {
            this.$message({
                message: this.$t('graduateBase.uploadFail'),
                type: 'error'
            })
        },
        // 下载导入模板
        downLoad() {
            examinationManagement.downloadTemplate().then(res => {
                this.$message({
                    type: 'success',
                    message: this.$t('internship.successfully')
                })
            })
        },

        changeSuccess(res, file, fileList) {
            if (res.code == 200) {
                this.$message({
                    type: 'success',
                    message: this.$t('internship.successfully')
                })
                this.queryForm.pageNum_ = 1
                this.postListQuestion(this.queryForm)
            } else if (res.msg) {
                this.$message({ type: 'info', message: res.msg })
            }
        },
        // 导出
        exportFile() {
            let projectIdList = []
            if (this.multipleSelection.length > 0) {
                projectIdList = this.multipleSelection.map(value => {
                    return value.id
                })
            }
            this.exportResult = null
            this.exportButton = true
            examinationManagement
                .questionExport({
                    idList: projectIdList,
                    questionPoolId: this.queryForm.condition.questionPoolId,
                    questionName: this.queryForm.condition.questionName
                })
                .then(res => {
                    if (res.code === 200 && res.data) {
                        let domIframe = document.createElement('iframe')
                        domIframe.src =
                            '/api/compulsoryservice/behavior/behaviorsysdictionary/downFile?path=' +
                            res.data
                        domIframe.style.display = 'none'
                        document.body.appendChild(domIframe)
                        this.$message.success(this.$t('导出成功'))
                    } else {
                        this.$message.success(this.$t('导出失败'))
                    }
                    this.exportResult = ''
                    this.exportButton = false
                })
        },
        // 搜索/筛选
        onSubmit() {
            this.queryForm.pageNum_ = 1
            this.postListQuestion(this.queryForm)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },

        // 重置
        reset() {
            for (let key in this.queryForm.condition) {
                this.queryForm.condition[key] = ''
            }
            this.fileList = []
            this.queryForm.pageNum_ = 1
            this.postListQuestion(this.queryForm)
        },
        // 保存
        conserve() {
            this.addflag = false
        },

        // 返回主页
        changeExam() {
            this.indexKey = 1
            this.multipleSelection = []
            this.queryForm.pageNum_ = 1
            this.postListQuestion(this.queryForm)
        },
        // 返回
        reback() {
            this.$router.push({
                path: '/examinationManagement',
                query: {
                    activeName: 'process'
                }
            })
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val
            // this.queryForm.pageNum_ = 1
            this.postListQuestion(this.queryForm)
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val
            this.postListQuestion(this.queryForm)
        }
    }
}
</script>
<style lang="scss" scoped>
.condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
}
.edu-page-title {
    span {
        line-height: 24px;
        display: inline-block;
        padding-right: 10px;
        font-size: 18px;
        font-weight: bold;
        color: #2b3b4e;
    }
}
.sub-title {
    margin: 16px 0;
    font-size: 16px;
    color: #000020;
    letter-spacing: 0;
}
.form-item {
    width: 312px;
    height: 32px;
    float: left;
    margin: 0px 10px;
}
.is-enabled-container ::v-deep {
    .el-button {
        cursor: auto;
    }
    .el-button--danger {
        padding: 9px 15px;
        min-width: 0;
    }
}
.inputBox {
    width: 240px !important;
    height: 32px !important;
}
.atooltip {
    background: beige;
    border: black;
}
</style>
